<template>
  <div>
    <QueryForm
      v-model="filters"
      :query-form-config="queryFormConfig"
      @handleQuery="getList(1)"
      @clear="clear"
    />
    <div v-if="meta.indexOf('GroupOpenBtn') > -1" class="doumee_table_header">
      <el-button
        v-if="meta.indexOf('GroupOpenBtn') > -1"
        v-preventReClick
        type="primary"
        @click="memberOpen"
      >团体会员开通</el-button>
    </div>
    <el-table
      ref="table"
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      :header-row-class-name="'table-header'"
      class="doumee-element-table"
    >
      <el-table-column
        align="center"
        label="团体名称"
        min-width="200"
        prop="teamName"
        show-overflow-tooltip
      >
        <template slot-scope="scope">
          <span @click="groupDetail(scope.row.teamId)">
            {{ scope.row.teamName }}
          </span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="管理员"
        prop="admin"
        min-width="140"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        label="会员卡类型"
        prop="cardType"
        min-width="200"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        label="累计签约金额"
        prop="amot"
        show-overflow-tooltip
        min-width="120"
      />
      <el-table-column
        align="center"
        label="账户余额"
        prop="zhye"
        show-overflow-tooltip
        min-width="120"
      />
      <el-table-column
        align="center"
        label="创建时间"
        prop="createDate"
        show-overflow-tooltip
        min-width="160"
      />
      <el-table-column label="操作" min-width="160" align="center" fixed="right">
        <template slot-scope="scope">
          <div class="flex-cc">
            <el-button
              v-preventReClick
              type="text"
              @click="editGroup(scope.row.teamId)"
            >编辑</el-button>
            <el-button
              v-preventReClick
              type="text"
              @click="backOut(scope.row.teamId)"
            >撤销</el-button>
            <el-popover
              :key="`popover-${scope.row.teamId}`"
              placement="bottom"
              width="120"
              class="el-pop-btns"
              trigger="hover"
            >
              <div>
                <div
                  v-preventReClick
                  class="moreBtn"
                  @click="reNew(scope.row.teamId)"
                >续签</div>
                <div
                  v-preventReClick
                  class="moreBtn"
                  @click="changeAdmintor(scope.row)"
                >更换管理员</div>
              </div>
              <el-button slot="reference" type="text" class="moreBtnShow">更多<i class="el-icon-caret-bottom primaryColor" /></el-button>
            </el-popover>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <!-- <div class="flex-cc doumee-pagination">
      <el-pagination
        background
        layout="prev, pager, next"
        :total="total"
        :current-page.sync="filters.page"
        hide-on-single-page
        @current-change="getList"
      />
    </div> -->
    <Paginations
      :total="total"
      :page="pagination.page"
      @current-change="getList"
      @SizeChange="handleSizeChange"
    />
    <el-dialog title="更换管理员" :visible.sync="showDetails" :before-close="cancelChangeAdmin" :close-on-click-modal="modalDialog" :close-on-press-escape="modalDialog">
      <el-form
        ref="ruleForm"
        class="doumee-form"
        :model="form"
        label-width="100px"
        label-suffix="："
      >
        <el-form-item label="原管理员">
          <el-input
            v-model="form.admin"
            disabled
            type="text"
            maxlength="20"
          />
        </el-form-item>
        <el-form-item label="新管理员">
          <el-input
            v-model="cardNum"
            placeholder="请输卡号/手机号"
            class="input-with-select bottom-speace-style"
            @keyup.enter.native="searchAction"
          >
            <el-button slot="append" icon="el-icon-search" @click="searchAction" />
          </el-input>
          <div v-if="showMessage" class="card-message">
            <div class="first-line">
              <span class="message-title-style">NO.</span>
              <span class="message-value-style">{{ cardMessage.number }}</span>
              <span class="message-value-style">{{ cardMessage.nickName }}</span>
              <span v-if="cardMessage.cardName" class="card-name-style">{{ cardMessage.cardName }}</span>
              <button class="message-title-style close-style" @click="closeMessage">x</button>
            </div>
            <div class="first-line">
              <span class="message-title-style">手机：</span>
              <span class="message-value-style">{{ cardMessage.phone }}</span>
              <span class="message-title-style">充值金额：</span>
              <span class="message-value-style">{{ cardMessage.remainingMoney?cardMessage.remainingMoney:0 }}</span>
              <span class="message-title-style">赠送金额：</span>
              <span class="message-value-style">{{ cardMessage.remainingGiveMoney?cardMessage.remainingGiveMoney:0 }}</span>
              <!-- <span class="message-title-style">余额：</span>
              <span class="message-value-style">{{ cardMessage.money }}</span> -->
            </div>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelChangeAdmin">取消</el-button>
        <el-button v-preventReClick type="primary" @click="confirmBtn">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listTeam, VIPInfo, memberTeamDelete, changTeamAdmin } from '@/api'
import { parseTime } from '@/utils/index'
import QueryForm from '@/components/QueryForm'
import store from '@/store'
export default {
  components: {
    QueryForm
  },
  props: {
    meta: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      modalDialog: store.getters.dialog,
      queryFormConfig: {
        formItems: [{
          filed: 'name',
          type: 'input',
          label: '团体名称',
          placeholder: '请输入团体名称',
          clearable: true
        }, {
          filed: 'admin',
          type: 'input',
          label: '管理员',
          placeholder: '请输入管理员',
          clearable: true
        }],
        online: true
      },
      list: [],
      listLoading: false,
      pagination: {
        page: 1,
        rows: 10
      },
      total: 0,
      cardNum: '',
      cardMessage: {},
      showMessage: false,
      venueId: sessionStorage.getItem('venueId'),
      filters: {},
      showDetails: false,
      form: {}
    }
  },
  created() {
    this.getList(1)
  },
  mounted() {
    this.$refs.table.doLayout()
  },
  methods: {
    memberOpen() {
      this.$router.push({ name: 'GroupOpen' })
    },
    closeMessage() {
      this.showMessage = false
      this.cardMessage = {}
      this.cardNum = ''
      this.form.id = ''
    },
    handleSizeChange(value) {
      this.pagination.rows = value
      this.getList(1)
    },
    searchAction() {
      // console.log('搜索会员卡')
      if (!this.cardNum.length) {
        this.$message.error('请输卡号/手机号')
        return
      }
      VIPInfo({
        param: {
          phoneOrNo: this.cardNum
        }
      })
        .then(res => {
          // console.log(res)
          if (res.errorCode === '000000') {
            this.cardMessage = res.record
            this.showMessage = true
            this.form.id = this.cardMessage.id
          }
        })
        .catch(err => {
          console.log(err)
          this.cardMessage = {}
          this.showMessage = false
        })
    },
    // 获取团体列表
    getList(page) {
      const { filters, pagination } = this
      if (page) {
        pagination.page = page
        this.pagination.page = page
      }
      pagination.firstQueryTime = parseTime(new Date())
      this.listLoading = true
      listTeam({
        param: {
          ...filters,
          venueId: sessionStorage.getItem('venueId')
        },
        pagination,
        userId: sessionStorage.getItem('userId')
      })
        .then((res) => {
          this.listLoading = false
          if (res.errorCode !== '000000') return
          this.list = res.recordList
          this.total = res.totalCount
          if (res.totalCount && res.recordList.length === 0 && pagination.page > 1) {
            this.getList(Math.ceil(res.totalCount / pagination.rows))
          }
        })
        .catch((err) => {
          console.log(err)
          this.listLoading = false
        })
    },
    // 团体详情
    groupDetail(id) {
      this.$router.push({ name: 'GroupDetails', query: { id: id }})
    },
    // 编辑团体
    editGroup(id) {
      this.$router.push({ name: 'GroupEdit', query: { id: id, isRenew: false }})
    },
    // 续签
    reNew(id) {
      this.$router.push({ name: 'GroupEdit', query: { id: id, isRenew: true }})
    },
    // 撤销团体
    backOut(teamId) {
      const that = this
      this.$confirm('此操作将撤销该团体, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        callback: () => {},
        beforeClose: (action, ctx, close) => {
          if (action !== 'confirm') {
            close()
            return
          }
          ctx.confirmButtonLoading = true
          memberTeamDelete({ param: { teamId }}).then((res) => {
            ctx.confirmButtonLoading = false
            close()
            if (res.errorCode === '000000') {
              that.$message.success('撤销成功')
              that.getList()
            }
          })
            .catch(() => { ctx.confirmButtonLoading = false })
        }
      }).finally(() => {})
    },
    // 取消更换管理员
    cancelChangeAdmin() {
      this.showDetails = false
      this.cardMessage = {}
      this.cardNum = ''
      this.showMessage = false
    },
    // 确认更换管理员
    confirmBtn() {
      if (!this.cardMessage.id) {
        this.$message.warning('请输卡号/手机号并搜索会员')
        return
      }
      changTeamAdmin({ param: {
        id: this.form.teamId,
        adminId: this.cardMessage.id,
        venueId: sessionStorage.getItem('venueId')
      }}).then((res) => {
        if (res.errorCode !== '000000') return
        this.showDetails = false
        this.$message.success('更换成功')
        this.getList()
      }).catch(() => {
      })
    },
    changeAdmintor(item) {
      this.$confirm('此操作将更换管理员, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.showDetails = true
          item = JSON.stringify(item)
          item = JSON.parse(item)
          this.form = item
          this.cardMessage = {}
        })
        .catch(() => {
          // this.$message.info('已取消操作')
        })
    },
    clear() {
      this.filters = {}
      this.getList(1)
    }
  }
}
</script>
<style lang="scss" scoped>
.card-message {
  margin-top: 10px;
  background-color: #f2f2f2;
  height: 60px;
  line-height: 20px;
  .first-line {
    height: 30px;
    padding: 5px;
    .message-title-style {
      color: #999;
    }
    .card-name-style {
      display: inline-block;
      border: 1px #999 solid;
      border-radius: 4px;
      background-color: #fff;
      font-size: 12px;
      padding-left: 5px;
      padding-right: 5px;
      height: 20px;
      text-align: center;
    }
    .close-style {
      font-size: 20px;
      float: right;
      margin-right: 5px;
      margin-top: -2px;
      padding: 0;
      border: 0px #999 solid;
    }
    .message-value-style {
      margin-right: 15px;
      color: #222;
    }
  }
}
</style>
